// pages/editNotice/editNotice.js
var request = require('../../operation/operation.js')
var klassModel = require('../../models/klass.js')
var bxt = require('../../utils/bxt.js')
var upyun = require('../../utils/upyun.js')
var noticeModel = require('../../models/notice.js')

var uploadedImageIndex = 0 // 当前上传图片序号
var formData = null; // 表单数据
var notice = null; // 要编辑的对象;null 添加模式,非null 编辑模式

Page({
  /**
   * 页面的初始数据
   */
  data: {
    title:'', // 通知标题
    content:'', // 通知文字内容
    images:[],  // 界面中显示的图片数据
    imageSize:0,  //  界面中显示的图片数量
    disabled: true, // 确定按钮可用/不可用控制
    loading: false, // 通信加载提示
    receiptRequirement: [],  // 签收通知要求
    currentReceiptRequirement: {} // 当前签收通知
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    noticeModel.resetReceiptRequirment()

    if (getApp().globalData.param) {    
      notice = getApp().globalData.param
      this.initView(notice)
    }else {  
      this.setData({
        receiptRequirement: noticeModel.RECEIPT_REQUIREMENT,
        currentReceiptRequirement: noticeModel.RECEIPT_REQUIREMENT[0]
      })
    }

    getApp().notificationCenter.register(bxt.SELECT_TITLE_MESSAGE, this, "handleSelectTitleMessage");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    uploadedImageIndex = 0
    formData = null
    notice = null

    getApp().notificationCenter.remove(bxt.SELECT_TITLE_MESSAGE, this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 单击签收通知按钮事件处理函数
   */
  onSelectRequirement:function(event) {
    noticeModel.resetReceiptRequirment()
    let requirements = noticeModel.RECEIPT_REQUIREMENT
    let requirement = event.currentTarget.dataset.requirement
    
    for (let index = 0; index < requirements.length; index++) {
      if (requirements[index].value == requirement.value) {
        requirements[index].check = true
        break;
      }else {
        requirements[index].check = false
      }
    }

    this.setData({
      receiptRequirement: requirements,
      currentReceiptRequirement: requirement
    })    
  },

  /**
   * 点击选择图片事件处理函数
   */
  chooseImage: function() {
    var that = this, length = 0, tmpfiles;
    if (that.data.images) {
      length = that.data.images.length
    }
    var size = 9 - length;
    wx.chooseImage({
      count: size,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        tmpfiles = that.data.images.concat(res.tempFilePaths)
        that.setData({
          images: tmpfiles,
          imageSize: tmpfiles.length
        })
      }
    })
  },

  /**
   * 点击图片预览事件处理函数
   */
  previewImage:function(event) {
      let that = this
    wx.previewImage({
      current: event.currentTarget.dataset.path, 
      urls: that.data.images
    })
  },

  /**
   * 点击删除图片事件处理函数
   */
  onDelImage:function(event) {
    var tmpfiles = this.data.images;
    tmpfiles.splice(event.currentTarget.id,1);
    this.setData({
      images: tmpfiles,
      imageSize: tmpfiles.length
    })
  },

  onNext:function(event) {
    formData = event.detail.value;
    formData.formId = event.detail.formId;
    
    getApp().createFormId(formData.formId)
    if (null == this.validateFormData(formData)) {      
      if (this.checkUploadImages()) { // 检查有没有要上传的图片
        this.uploadImage();
      }else {
        // 没有图片直接上传通知
        this.uploadNotice();
      }
    }
  },

  onShowEditTitle:function(event) {    
    var title = ''
    if (this.data.title) {
      title = this.data.title
    }
    wx.navigateTo({
      url: '../editNoticeTitle/editNoticeTitle?title=' + title   
    })
  },

  /**
   * 检查要提交数据的完整性
   * param object data 表单中必填的数据
   * return null 或者 非null
   */
  validateFormData:function(data){
    var message = null;
    if (0 == data.title.length) {
      message = "请输入通知标题";
    } 

    if (message) {
      wx.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    }
    
    return message;
  },

  /**
   * 获取需要上传服务器的图片
   * return array
   */
  checkUploadImages:function() {
    var result = false

    for (var index = 0; index < this.data.images.length; index++) {
      if (this.data.images[index].indexOf('://tmp') > 0) { // 包含http://tmp/ 字符串认为是本地新选择的文件
        result = true
        break
      }
    }

    return result
  },

  /**
   * 上传图片到又拍云
   */
  uploadImage:function() {
    var that = this
    if(uploadedImageIndex + 1 <= this.data.images.length) {  
      this.setButtonLoading(true)

      if (0 > this.data.images[uploadedImageIndex].indexOf('://tmp')) {        
        uploadedImageIndex++
        this.uploadImage()
        return
      }
      
      upyun.uploadImage(this.data.images[uploadedImageIndex],
        bxt.UP_YUN_IMAGE_PATH,
        function (filePath, videoThumbnail) {
          that.data.images[uploadedImageIndex] = filePath
          uploadedImageIndex++
          that.uploadImage()
        },
        function(fail) {
          wx.showToast({
            title: fail,
            icon:none
          })
          that.setButtonLoading(false)
        })
     
    }else {
      // 图片上传完成处理流程
      that.uploadNotice();
    }
  },

  /**
   * 创建通知
   */
  uploadNotice:function() {
    var that = this
    var params = new Object();
    params.title = formData.title;
    params.formId = formData.formId;
    params.receiptRequirement = this.data.currentReceiptRequirement.value
    if (0 < formData.content.length) {
      params.content = formData.content;
    }else {
      params.content = ''
    }
    if (this.data.images) {
      params.images = this.data.images.join('|');
    }else {
      params.images = ''
    }

    this.setButtonLoading(true)
    var method = 'POST', path = '/notices'
    if (notice) {
      method = 'PUT';
      path += '/' + notice.sid;
    }
    
    request.startRequest(method, path, params, true)
      .then(res => {
        that.setButtonLoading(false)
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          getApp().globalData.param = data.object
          getApp().notificationCenter.post(bxt.REFRESH_NOTICES_MESSAGE)
          getApp().notificationCenter.post(bxt.REFRESH_NOTICE_MESSAGE)      
          if (notice) {            
            wx.showToast({
              title: '编辑成功',
            })

            setTimeout(function (){
              wx.navigateBack({
                
              })}
            ,1500)
          }else {
            wx.redirectTo({
              url: '../noticePreview/noticePreview',
            })
          }          
        }else {
          wx.showToast({
            title: data.msg,
            icon:'none'
          })
        }

      }).catch(e => {
        that.setButtonLoading(false)
        console.log(e)
      })
  },
  
   /**
   * 设置按钮状态
   */
  setButtonLoading: function (loading) {
    this.setData({
      disabled: loading,
      loading: loading
    })
  },

  /**
   * 初始化界面
   */
  initView:function(notice) {
    var imageSize = 0,images = []
    if (notice.imagesArray) {
      imageSize = notice.imagesArray.length
      for (let index = 0; index < imageSize; index++) {
        images.push(notice.imagesArray[index].url)
      }
    }
    this.setData({
      title:notice.title,
      content:notice.content,
      images: images,
      imageSize: imageSize
    })

    if (notice.receiptRequirement) {
      this.setData({
        receiptRequirement: noticeModel.getReceiptRequirements(notice.receiptRequirement),
        currentReceiptRequirement: noticeModel.getReceiptRequirement(notice.receiptRequirement)
      })
    }

    this.updateDisabledState(notice);
  },

  /**
   * 接收选择标题事件处理函数
   */
  handleSelectTitleMessage: function (object) {
    let that = this
    this.setData({
      title: object.title
    });

    this.updateDisabledState(object);
  },

  /**
   * 判断通知标题是否存在，更新"确定"按钮可用状态
   */
  updateDisabledState: function(notice){
    let disabled = true;
    if (notice.title.length > 0){
      disabled = false;
    }

    this.setData({
      disabled: disabled
    });
  }
})